import type { IMenu } from '@/interface/IMenu'
import router from '@/router'
import { defineStore } from 'pinia'
import { ref, watch, type Ref } from 'vue'

export const useRouteStore = defineStore('route', () => {
  const activeIndex: Ref<number> = ref(1)
  const targetPage: Ref<string> = ref('')
  const menu: Ref<IMenu[]> = ref([])
  // 侦听activeIndex的变化,只要发生改变就会更新页面(跳转到对应的页面)
  watch(activeIndex, (value: number) => {
    
    getRouteByAcIndex(activeIndex.value)
  })
  // 根据acIndex获取对应路由路径的函数
  function getRouteByAcIndex(index: number) {
    // 拿到这个数据去找对应的路由 侦听activeIndex发生变化，我们就去找对应的路由path
    menu.value.forEach((item) => {
      // 单页面只用一层循环  如果子菜单项多层的话的话表示菜单会有children 就要多n层循环
      if (index == Number(item.index)) {
        targetPage.value = item.route
        router.push({ path: targetPage.value })
        return;
      } else {
        item.children?.forEach((child) => {
          if (index == Number(child.index)) {
            targetPage.value = child.route
            router.push({ path: targetPage.value })
            return;
          }
        })
      }
    })
  }
  return { activeIndex, targetPage, menu, getRouteByAcIndex }
}, {
  persist: {
    storage: sessionStorage,
    key: "route"
  }
})

